package com.xiaochong.tir.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.api.util.ListSortPageUtil;
import com.xiaochong.tir.api.util.ListSortUtil;
import com.xiaochong.tir.api.util.StringUtil;
import com.xiaochong.tir.common.data.mapper.SelfSelectedMapper;
import com.xiaochong.tir.common.data.mapper.SelfSelectedSortMapper;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.po.SelfSelected;
import com.xiaochong.tir.common.data.po.SelfSelectedSort;
import com.xiaochong.tir.common.data.vo.ApiKActionQuantizationVo;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.data.vo.CurrencyQuotationResultVo;
import com.xiaochong.tir.common.util.ApiResultCodeUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @Description: 自选
 * @Author: org
 * @CreateDate: 2018/7/25 11:28
 */
@Service
public class ShelSelectService {

    @Autowired
    private SelfSelectedMapper selfSelectedMapper;
    @Autowired
    private RedisServer redisServer;
    @Autowired
    private ImmortalsService immortalsService;
    @Autowired
    private SelfSelectedSortMapper selfSelectedSortMapper;
    /**
     * 货币和交易对加入自选
     * @param type
     * @param userToken
     * @param unique_annotation
     * @return
     */
    public ApiResultVo joinAndCancelShelSelect(Integer type, String userToken, Integer unique_annotation,Integer flagType) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(null == type || null == unique_annotation || null == flagType){//PARAMS_ERROR
                resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
                resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
                return resultVo;
            }
            Integer user_id = getRedisUserId(userToken);
            if(user_id == null){
                resultVo.setCode(ApiResultCodeUtils.TOKEN_ERROR.getCode());
                resultVo.setMessage(ApiResultCodeUtils.TOKEN_ERROR.getMsg());
                return resultVo;
            }
            LogTrace.infoKvs("加入自选","type",type.toString(),"user_id",user_id.toString(),"unique_annotation",unique_annotation.toString(),"flagType",flagType.toString());
            SelfSelected selfSelected = new SelfSelected();
            selfSelected.setType(type.toString());
            selfSelected.setUniqueAnnotation(unique_annotation);
            selfSelected.setUserId(user_id);
            int deleteOrInsertInt = 0;
            if(1 == flagType){
                //验证是否已经存在
                List<SelfSelected> list = selfSelectedMapper.selectByEntityList(selfSelected);
                if(list == null || list.size() == 0){
                    selfSelected.setCreateTime(new Date());
                    //deleteOrInsertInt = selfSelectedMapper.insert(selfSelected);
                    deleteOrInsertInt = selfSelectedMapper.insertReturnId(selfSelected);
                    if(selfSelected.getId() != null && deleteOrInsertInt == 1){
                        Map<String,Object> params = new HashMap();
                        params.put("type",1);
                        params.put("userId",user_id);
                        params.put("sort",selfSelected.getId()+",");
                        int congInt = 0;
                        congInt =selfSelectedSortMapper.updateByInsertOrDelete(params);
                        if(congInt == 0){
                            SelfSelectedSort selfSelectedSort = new SelfSelectedSort();
                            selfSelectedSort.setSort(selfSelected.getId()+",");
                            selfSelectedSort.setUserId(user_id);
                            deleteOrInsertInt = selfSelectedSortMapper.insert(selfSelectedSort);
                        }
                    }
                }
            }else if(2 == flagType){
                selfSelected = selfSelectedMapper.selectByEntity(selfSelected);//查询id
                if(selfSelected.getId() != null){
                    deleteOrInsertInt = selfSelectedMapper.deleteByEntity(selfSelected);
                    if(deleteOrInsertInt == 1){
                        Map<String,Object> params = new HashMap();
                        params.put("type",2);
                        params.put("userId",user_id);
                        params.put("sort",selfSelected.getId()+",");
                        selfSelectedSortMapper.updateByInsertOrDelete(params);
                    }
                }
                //deleteOrInsertInt = selfSelectedMapper.deleteByPrimaryKey(selfSelected.getId());
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                return resultVo;
            }
            //判断是否插入/删除成功
            if(deleteOrInsertInt > 0){
                resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
                resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("加入自选",e);
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        return resultVo;
    }

    /**
     * k线行情自选
     * @param pageIndex
     * @param pageSize
     * @param userToken
     *@param sortField
     * @param userToken  @return
     */
    public ApiResultVo<List<ApiKActionQuantizationVo>> kActionMarketSelfSelect(Integer pageIndex, Integer pageSize,
                                                                               String userToken, String sortField, String sortType) {
        ApiResultVo<List<ApiKActionQuantizationVo>> resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        List<ApiKActionQuantizationVo> vo = new ArrayList<>();
        try {
            if(null == pageIndex || null == pageSize){//PARAMS_ERROR
                resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
                resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
                return resultVo;
            }
            Integer user_id = getRedisUserId(userToken);
            if(user_id == null){
                resultVo.setCode(ApiResultCodeUtils.TOKEN_ERROR.getCode());
                resultVo.setMessage(ApiResultCodeUtils.TOKEN_ERROR.getMsg());
                return resultVo;
            }
            ApiKActionQuantizationVo apiKActionQuantizationVo;
            LogTrace.infoKvs("k线行情自选","pageSize",pageSize.toString(),"user_id", String.valueOf(userToken),"pageIndex",pageIndex.toString(),"userToken",String.valueOf(userToken));
            //分页查询自选币
            //PageHelper.startPage(pageIndex,pageSize);
            List<ExchangeTransactionpairMiddle>  curencyList = selfSelectedMapper.selectSelfPairSelectByUserId(user_id);
           // PageInfo<ExchangeTransactionpairMiddle> selfList = new PageInfo<>(curencyList);
            //根据货币查找对应的k线数据
            ExchangeTransactionpairMiddle middle ;
            String redisKey = "";
            int curencyListSize =0;
            int pages =0;
            if(curencyList != null){
                curencyListSize = curencyList.size();
            }
            if(curencyList != null && curencyListSize > 0){
                for(int i =0;i<curencyList.size();i++){
                    middle = curencyList.get(i);
                    if(middle.getExchangeId() != null && StringUtils.isNotBlank(middle.getTransactionName())){
                        redisKey = RedisKeysUtils.K_ACTION_SELF_SELECT+"@"+middle.getExchangeId()+"@"+middle.getTransactionName();
                        String data = redisServer.get(redisKey);
                        if(StringUtils.isNotBlank(data)){
                            apiKActionQuantizationVo = JSON.parseObject(data,ApiKActionQuantizationVo.class);
                            if(apiKActionQuantizationVo != null){
                                vo.add(apiKActionQuantizationVo);
                            }
                        }
                    }
                }
                //排序
                /*if(vo == null || vo.size() == 0){
                    resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                    resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
                    return resultVo;
                }*/
                //排序--根据排序取出对应的条数对应的页数的数据返回前端
                if(StringUtils.isNotBlank(sortField)){//设置默认排序字段是当前价格
                    if(StringUtils.isBlank(sortType)){//设置默认排序为降序
                        sortType = "desc";
                    }
                    ListSortUtil util=new ListSortUtil();
                    util.mySort( vo, sortField.trim(), sortType );
                    //排名
                    if (curencyListSize>0){
                        for (int i=0;i<curencyListSize;i++){
                            vo.get( i ).setRank( i+1 );
                        }
                    }
                }
                vo= ListSortPageUtil.pageBean(vo,pageIndex,pageSize);
            }
            //计算页数
            pages = curencyListSize/pageSize;
            int yu = curencyListSize%pageSize;
            if(yu > 0){
                pages = pages+1;
            }
            //是否存在自选
            if(curencyListSize > 0){
                resultVo.setTotal(curencyListSize);
                resultVo.setPages(pages);
                resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
                resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
            }
            resultVo.setData(vo);
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("k线行情自选",e);
            e.printStackTrace();
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        return resultVo;
    }

    /**
     * 货币自选
     * @param pageIndex
     * @param pageSize
     * @param userToken
     * @return
     */
    public ApiResultVo currencyQuotationSelfSelect(Integer pageIndex, Integer pageSize, String userToken,
                                                   String sortField,String sortType) {
        ApiResultVo<List<CurrencyQuotationResultVo>> resultVo = new ApiResultVo<>();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        List<CurrencyQuotationResultVo> vo = new ArrayList<>();
        try {
            if(null == pageIndex || null == pageSize){//PARAMS_ERROR
                resultVo.setCode(ApiResultCodeUtils.PARAMS_ERROR.getCode());
                resultVo.setMessage(ApiResultCodeUtils.PARAMS_ERROR.getMsg());
                return resultVo;
            }
            Integer user_id = getRedisUserId(userToken);
            if(user_id == null){
                resultVo.setCode(ApiResultCodeUtils.TOKEN_ERROR.getCode());
                resultVo.setMessage(ApiResultCodeUtils.TOKEN_ERROR.getMsg());
                return resultVo;
            }
            LogTrace.infoKvs("货币行情自选","pageSize",pageSize.toString(),"user_id",String.valueOf(user_id),"pageIndex",pageIndex.toString(),"userToken",String.valueOf(userToken));
            //分页查询自选币
            CurrencyQuotationResultVo currencyQuotationResultVo ;
            //PageHelper.startPage(pageIndex,pageSize);
            List<CurrencyInfo>  curencyList = selfSelectedMapper.selectCoinSelfSelectByUserId(user_id);
            //PageInfo<CurrencyInfo> selfList = new PageInfo<>(curencyList);
            int curencyListSize =0;
            int pages =0;
            if(curencyList != null){
                curencyListSize = curencyList.size();
            }
            //根据货币查找对应的k线数据
            if(curencyList != null && curencyList.size() > 0) {
                for (CurrencyInfo currencyInfo:curencyList) {
                    currencyQuotationResultVo = immortalsService.getCurrencyByCmcId(currencyInfo.getCmcId());
                    if(currencyQuotationResultVo != null){
                        vo.add(currencyQuotationResultVo);
                    }
                }
                //排序--根据排序取出对应的条数对应的页数的数据返回前端
                if(StringUtils.isNotBlank(sortField)){//设置默认排序字段是当前价格
                    if(StringUtils.isBlank(sortType)){//设置默认排序为降序
                        sortType = "desc";
                    }
                    ListSortUtil util=new ListSortUtil();
                    util.mySort( vo, sortField.trim(), sortType );
                    //排名
                    if (curencyListSize>0){
                        for (int i=0;i<curencyListSize;i++){
                            vo.get( i ).setRank( i+1 );
                        }
                    }
                }
                vo= ListSortPageUtil.pageBean(vo,pageIndex,pageSize);
            }
            //计算页数
            pages = curencyListSize/pageSize;
            int yu = curencyListSize%pageSize;
            if(yu > 0){
                pages = pages+1;
            }
            //是否存在自选
            if(curencyListSize > 0){
                resultVo.setTotal(Integer.valueOf(String.valueOf(curencyListSize)));
                resultVo.setPages(pages);
                resultVo.setCode(ApiResultCodeUtils.BASE_SUCCESS.getCode());
                resultVo.setMessage(ApiResultCodeUtils.BASE_SUCCESS.getMsg());
            }else{
                resultVo.setCode(ApiResultCodeUtils.SYSTEM_NULL.getCode());
                resultVo.setMessage(ApiResultCodeUtils.SYSTEM_NULL.getMsg());
            }
            resultVo.setData(vo);
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("货币行情自选",e);
            e.printStackTrace();
            resultVo.setCode(ApiResultCodeUtils.SYSTEM_ERROR.getCode());
            resultVo.setMessage(ApiResultCodeUtils.SYSTEM_ERROR.getMsg());
        }
        return resultVo;
    }

    /**
     * 根据用户token判断此交易对和货币是否已自选
     * @param userToken 用户token
     * @param uniqueAnnotation 中间表id
     * @param type 1：交易对自选 2：货币自选
     * @return 2：未自选 1：已自选
     */
    public Integer valicatSymbolSelfSelect(String userToken,Integer uniqueAnnotation,Integer type){
        Integer selfSelectFlag = 2;
        Integer user_id = getRedisUserId(userToken);
        if(user_id != null){
            List<Integer> middleList = new ArrayList<>();
            middleList.add(uniqueAnnotation);
            if(middleList.size() > 0){
                Map<String,Object> params = new HashMap<>();
                params.put("type",type);
                params.put("uniqueAnnotationList",middleList);
                params.put("user_id",user_id);
                List<SelfSelected> selfList = selfSelectedMapper.getSelfSelectByMideleId(params);
                if(selfList != null && selfList.size()>0){
                    return 1;
                }
            }
        }
        return selfSelectFlag;
    }
    /**
     * 根据用户token获取userId
     * @param userToken
     * @return
     */
    public Integer getRedisUserId(String userToken){
        //获取redis用户信息,redis存在用户id并且token验证成功才能进入系统，否则返回失败
        String userStr = redisServer.get(RedisKeysUtils.TIR_USER_TOKEN+userToken);
        if(StringUtils.isNotBlank(userStr)){
            JSONObject userObject = JSON.parseObject(userStr);
            if(userObject != null ){
                String data = JSON.toJSONString(userObject.get("data"));
                if(StringUtils.isNotBlank(data)){
                    Integer userId = Integer.valueOf(JSON.parseObject(data).get("userId").toString());
                    if(userId != null){//验证登录成功
                        return  userId;
                    }
                }
            }
        }
        return  null;
    }
}
